﻿using System;
using System.Collections.Generic;
using System.Linq;
using Startup.MVVM;
using Startup.Shell.Domain;
using Startup.Shell.ModelDesignerPreview;
using Startup.Shell.Modules.PreviewDesignerCtrlModule;

namespace Startup.Shell.Modules.PreviewDesignerHierarchyModule
{
	public class PreviewDesignerHierarchyViewModel : ViewModelBase
	{
		private readonly StartupProject _startupProject;
		private readonly PreviewContainer _source;
	    private readonly StartupClass _domainClass;

		public PreviewDesignerHierarchyViewModel(StartupProject startupProject, PreviewContainer source, StartupClass domainClass)
		{
			_startupProject = startupProject;
			_source = source;
		    _domainClass = domainClass;

			_source.PreviewChanged += OnSourcePreviewChanged;
		}

		private void OnSourcePreviewChanged()
		{
            if (_source.Preview != null)
            {
                for (int index = 0; index < _source.Preview.Children.Length; index++)
                    _source.Preview.Children[index].DataContextPropertyId = _source.DataContextPropertyId;
            }

			RaisePropertyChanged("Children");
		}

		public PreviewDesignerCtrlModelView Source
		{
			get { return new PreviewDesignerCtrlModelView(_startupProject, _source, _domainClass); }
		}

		public IList<PreviewDesignerHierarchyViewModel> Children
		{
			get { return _source.Preview == null ? new PreviewDesignerHierarchyViewModel[0] : _source.Preview.Children.Select(x => new PreviewDesignerHierarchyViewModel(_startupProject, x, _domainClass)).ToArray(); }
		}

		public static PreviewDesignerHierarchyViewModel Designer
		{
			get
			{
				var mainWindow = new WindowDesignerPreview();
				mainWindow.Children[0] = new PreviewContainer { Preview = new WindowDesignerPreview() };

				return new PreviewDesignerHierarchyViewModel(new StartupProject(), new PreviewContainer { Preview = mainWindow }, new StartupClass());
			}
		}
	}
}
